package com.example.sps.commons;

import org.springframework.core.NestedRuntimeException;
import org.springframework.core.convert.ConversionException;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @ProjectName: Sps
 * @Titile: GlobalExceptionHandler
 * @Author: nency
 * @Description: 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public R<Void> serviceExceptionHandle(ServiceException e){
//        R<Void> r = new R<>();
//        r.setMessage(e.getMessage());
//        r.setCode(e.getServiceCode().getCode());
        return R.fail(e);
    }
    @ExceptionHandler
    public R<Void> validateExceptionHandle(HttpMessageConversionException e){
//        R<Void> r = new R<>();
//        r.setMessage("数据传递出现异常，数据类型传的参数有误");
//        r.setCode(ServiceCode.ERROR_BAD_REQUEST.getCode());
//        return r;
        return R.fail(new ServiceException(ServiceCode.ERROR_BAD_REQUEST,"传递的数据类型或值错误，请检查."));
    }
    @ExceptionHandler
    public R<Void> bindExceptionHandle(BindException e){
//        R<Void> r = new R<>();
//        r.setMessage(e.getCause().getMessage());
//        r.setCode(ServiceCode.ERROR_BAD_REQUEST.getCode());
//        return r;
        return R.fail(new ServiceException(ServiceCode.ERROR_BAD_REQUEST,e.getFieldError().getDefaultMessage()));
    }
    @ExceptionHandler
    public R<Void> bindExceptionHandle(Throwable e){
        //打印异常的堆栈信息，是堵塞式的，项目上线后，一定要注释掉
        e.printStackTrace();
        R<Void> r = new R<>();
        r.setMessage("服务器异常，请联系管理员");
        r.setCode(ServiceCode.ERROR_UNKNOWN.getCode());
        return r;
    }
}
